package com.example.firstapp.notice

import android.app.Activity
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.media.ExifInterface
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import androidx.core.app.NotificationCompat
import androidx.core.content.FileProvider
import com.example.firstapp.R
import com.example.firstapp.databinding.ActivityContactsListViewBinding
import com.example.firstapp.databinding.ActivityNoticeBinding
import java.io.File

class NoticeActivity : AppCompatActivity() {
    val takePhoto = 1
    val fromAlbum = 2
    lateinit var imageUri: Uri
    lateinit var outputImage: File
    lateinit var binding: ActivityNoticeBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_notice)
        binding= ActivityNoticeBinding.inflate(layoutInflater)
        setContentView(binding.root)
        // getSystemService() 获取系统级服务
        // NOTIFICATION_SERVICE 指定通知服务
        // 强制转型为 NotificationManager对象
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as
                NotificationManager
        // Build.VERSION.SDK_INT 检测设备系统版本，仅当 ≥ Android 8.0 Oreo的常量（值为26）时执行渠道创建（旧版本无需渠道）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 创建渠道
            // 参数1 渠道id  参数2 渠道名称
            // 参数3 重要性：IMPORTANCE_DEFAULT 发出声音并在状态栏显示
            //             IMPORTANCE_HIGH 紧急通知（声音+弹出）
            //             IMPORTANCE_LOW  无声音，仅状态栏
            val channel = NotificationChannel("normal", "Normal", NotificationManager.
            IMPORTANCE_DEFAULT)
            val channel2 = NotificationChannel("important", "important", NotificationManager.
            IMPORTANCE_HIGH)
            // 绑定渠道到通知管理
            manager.createNotificationChannel(channel)
            manager.createNotificationChannel(channel2)
        }
        binding.notice1.setOnClickListener {
            val intent1 = Intent(this, PendingIntentActivity1::class.java)
            val pi = PendingIntent.getActivity(this,0,intent1, PendingIntent.FLAG_IMMUTABLE)
            val notification1 = NotificationCompat.Builder(this,"normal")
                .setContentTitle("通知标题")
                .setContentText("这是通知的内容")
                .setSmallIcon(R.drawable.apple_pic)
                // 转换成Bitmap
                .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.banana_pic))
                .setContentIntent(pi)
                .setAutoCancel(true)  // 点击通知后消失
                .build()
            // 将通知的内容绑定到通知管理上
            manager.notify(1,notification1)
        }

        binding.notice2.setOnClickListener {
            val intent1 = Intent(this, PendingIntentActivity1::class.java)
            val pi = PendingIntent.getActivity(this,0,intent1, PendingIntent.FLAG_IMMUTABLE)
            val notification1 = NotificationCompat.Builder(this,"important")
                .setContentTitle("通知标题")
                .setContentText("这是通知的内容")
                .setStyle(NotificationCompat.BigTextStyle().bigText("Learn how to build notifications, " +
                        "send and sync data, and use voice actions. Get the official Android IDE and developer" +
                        " tools to build apps for Android."))  //长文字 替代setContentText
                .setStyle(NotificationCompat.BigPictureStyle().bigPicture(
                    BitmapFactory.decodeResource(resources, R.drawable.a)))  //显示大图片
                .setSmallIcon(R.drawable.apple_pic)
                // 转换成Bitmap
                .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.banana_pic))
                .setContentIntent(pi)
                .setAutoCancel(true)  // 点击通知后消失
                .build()
            // 将通知的内容绑定到通知管理上
            manager.notify(1,notification1)
        }

        binding.camera.setOnClickListener {
            // 创建File对象，用于存储拍照后的图片,externalCacheDir是系统关联目录 可以无需权限直接访问
            outputImage = File(externalCacheDir,"output_image.jpg")
            if (outputImage.exists()){
                outputImage.delete()
            }
            outputImage.createNewFile()
            imageUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                // 新版本安全访问
                FileProvider.getUriForFile(this,"com.example.firstapp.fileprovider", outputImage)
            }else{
                // 旧版本直接获取文件路径
                Uri.fromFile(outputImage)
            }
            // 启动相机程序
            val intent = Intent("android.media.action.IMAGE_CAPTURE")
            intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri)  //指定图片输出地址
            startActivityForResult(intent, takePhoto) //启动相机
        }

        binding.picture.setOnClickListener {
            // 打开文件选择器
            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
            intent.addCategory(Intent.CATEGORY_OPENABLE)
            // 指定只显示图片
            intent.type = "image/*"
            startActivityForResult(intent, fromAlbum)
        }

        // 播放视频
        val uri =Uri.parse("android.resource://$packageName/${R.raw.video}")
        binding.videoView.setVideoURI(uri)
        binding.play.setOnClickListener {
            if (!binding.videoView.isPlaying){
                binding.videoView.start()
            }
        }
        binding.pause.setOnClickListener {
            if (binding.videoView.isPlaying){
                println(1)
                binding.videoView.pause()
            }
        }
        binding.replay.setOnClickListener {
                binding.videoView.start()
                binding.videoView.resume()
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        binding.videoView.suspend()
    }
    // 使用startActivityForResult()启动Activity的，拍照结果返回到onActivityResult()方法
    override fun onActivityResult(requestCode:Int,resultCode: Int, data: Intent?){
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            takePhoto -> {   // 当requestCode=takePhoto=1
                if (resultCode == Activity.RESULT_OK){  //RESULT_OK(-1)成功   RESULT_CANCELED(0)取消
                    // 将拍摄的照片显示出来
                    // ContentResolver 安全访问文件
                    // 将输入流解码为 Bitmap 对象
                    var bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(imageUri))
                    binding.imageView.setImageBitmap(rotateIfRequired(bitmap))
                }
            }
            fromAlbum -> {
                if (resultCode == Activity.RESULT_OK && data != null) {
                    data.data?.let { uri ->
                        // 将选择的图片显示
                        val bitmap = getBitmapFromUri(uri)
                        binding.imageView.setImageBitmap(bitmap)
                    }
                }
            }
        }
    }
    private fun rotateIfRequired(bitmap: Bitmap): Bitmap {
        // 创建 EXIF 接口对象读取照片方向信息
        val exif = ExifInterface(outputImage.path)
        val orientation = exif.getAttributeInt(
            ExifInterface.TAG_ORIENTATION,
            ExifInterface.ORIENTATION_NORMAL)
        return when (orientation) {
            ExifInterface.ORIENTATION_ROTATE_90 -> rotateBitmap(bitmap, 90)
            ExifInterface.ORIENTATION_ROTATE_180 -> rotateBitmap(bitmap, 180)
            ExifInterface.ORIENTATION_ROTATE_270 -> rotateBitmap(bitmap, 270)
            else -> bitmap
        }
    }
    private fun rotateBitmap(bitmap: Bitmap, degree: Int): Bitmap {
        val matrix = Matrix()
        matrix.postRotate(degree.toFloat())
        val rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height,
            matrix, true)
        bitmap.recycle() // 将不再需要的Bitmap对象回收
        return rotatedBitmap
    }

    private fun getBitmapFromUri(uri: Uri) = contentResolver
        .openFileDescriptor(uri, "r")?.use {
            BitmapFactory.decodeFileDescriptor(it.fileDescriptor)
        }
}